import { getNodeByNodeId } from '@/utils/work';
import React, { useEffect, useRef, useState } from 'react';
import { model } from '../../../ts/base';
import DetailForms from './detail';
import PrimaryForms from './primary';
import { IBelong } from '@/ts/core';
import WorkFormService from '@/ts/scripting/core/services/WorkFormService';

interface IWorkFormProps {
  allowEdit: boolean;
  belong: IBelong;
  nodeId: string;
  data: model.InstanceDataModel;
  service?: WorkFormService;
  isDone?: boolean;
  splitDetailFormId?: string;
}

/** 流程节点表单 */
const WorkForm: React.FC<IWorkFormProps> = (props) => {
  const [node, setNode] = useState<model.WorkNodeModel>();
  const service = useRef(props.service);
  useEffect(() => {
    const node = getNodeByNodeId(props.nodeId, props.data.node);
    if (!service.current) {
      service.current = new WorkFormService(props.belong, props.data, props.allowEdit);
      service.current.init();
    }
    setNode(node);
  }, [props.data]);
  if (!node || !service.current) return <></>;
  return (
    <div style={{ padding: 10 }}>
      {node.primaryForms && node.primaryForms.length > 0 && (
        <PrimaryForms service={service.current} node={node} />
      )}
      {node.detailForms && node.detailForms.length > 0 && (
        <DetailForms
          service={service.current}
          node={node}
          isDone={props.isDone}
          splitDetailFormId={props.splitDetailFormId}
        />
      )}
    </div>
  );
};

export default WorkForm;
